package leetcode.题库.矩阵;

import java.util.Arrays;

/**
 * @author yanzhenming
 * @date 2023/3/13  23:03
 */
public class Solution59 {
    public static void main(String[] args) {
        System.out.println(Arrays.deepToString(generateMatrix(3)));
    }

    public static int[][] generateMatrix(int n) {
        int num = 1;
        int l = 0, r = n-1, t = 0, b = n-1;
        int[][] res = new int[n][n];
        // 按层打印，每次分四次打印
        while (num <= n*n) {
            // 打印上层
            for (int i = l; i <= r; i++) {
                res[t][i] = num++;
            }
            // 打印右侧
            for (int i = t+1; i <= b; i++) {
                res[i][r] = num++;
            }
            // 打印下侧
            for (int i = r-1; i >= l; i--) {
                res[b][i] = num++;
            }
            // 打印左侧
            for (int i = b-1; i >= t+1; i--) {
                res[i][l] = num++;
            }
            l++;r--;t++;b--;
        }
        return res;
    }
}
